/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.jpa.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.bastion.query.Matcher;
import org.bastion.service.FindService;
import org.bastion.service.QueryService;
import org.bastion.service.RegisterService;

public class JpaService implements RegisterService, FindService, QueryService {

	private final EntityManager em;

	public JpaService(EntityManager em) {
		this.em = em;
	}

	public Long register(Object object) {
		em.persist(object);
		return null;
	}

	public <T> T find(Class<T> clazz, Object key) {
		return em.find(clazz, key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> executeQuery(Class<T> clazz) {
		Query query = em.createQuery("select a from " + clazz.getSimpleName() + " a");
		return query.getResultList();
	}

	@Override
	public <T> List<T> executeQuery(Class<T> clazz, Matcher<T> matcher) {
		List<T> tempList = executeQuery(clazz);
		List<T> resultList = new ArrayList<T>();
		for (T object : tempList) {
			if (matcher.match(object)) {
				resultList.add(object);
			}
		}
		return resultList;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> executeQuery(Class<T> clazz, String queryName, Map<String, Object> parameters) {
		Query query = em.createNamedQuery(queryName);
		if (parameters != null) {
			for (String parameter : parameters.keySet()) {
				query.setParameter(parameter, parameters.get(parameter));
			}
		}
		return query.getResultList();
	}

	@Override
	public boolean prefersNamedQueries() {
		return true;
	}

	@Override
	public boolean prefersPredicateQueries() {
		return false;
	}

	@Override
	public boolean supportsNamedQueries() {
		return true;
	}

	@Override
	public boolean supportsPredicateQueries() {
		return false;
	}

}
